// src/services/scholarsDashboardService/tableScholarRecords.ts

import { BASE_URL } from '@/services/apiConfig';

interface ScholarRecordParams {
  skip?: number;
  limit?: number;
}

interface ScholarRecord {
  program: string | null;
  year: number | null;
  student_number: string | null;
  first_name: string | null;
  preferred_name: string | null;
  last_name: string | null;
  default_email: string | null;
  alternate_email: string | null;
  university_status: string | null;
  date_of_birth: string | null;
  gender: string | null;
  school_code: string | null;
  school_name: string | null;
  gateway_school: string | null;
  indigenous_student: string | null;
  start_date: string | null;
  end_date: string | null;
  scholar_type: string | null;
  dietary_preference: string | null;
  dietary_allergies: string | null;
  dietary_religious: string | null;
  medical_allergies: string | null;
  ite_number: number | null;
  sponsor_name: string | null;
  department: string | null;
  supervisors: string | null;
  ite_start: string | null;
  ite_end: string | null;
  ite_details_input_date: string | null;
  ite_input_in_time: boolean | null;
  latest_start_date: string | null;
  expected_finish_date: string | null;
  start_date_met: boolean | null;
  end_date_met: boolean | null;
  it_change_approved: string | null;
  pd_agreement_submission_date: string | null;
  // pd_submitted_on_time: boolean | null;
  placement_mid_point: string | null;
  mpc_call_date: string | null;
  mpc_call_on_time: string | null;
  mpc_document_due_date: string | null;
  mpc_submitted_date: string | null;
  mpc_submitted_on_time: string | null;
  end_of_it_presentation_date: string | null;
  end_of_it_input_date: string | null;
  it_presentation_completed_ontime: string | null;
  unsw_attendee_on_presentation: string | null;
  sponsor_evaluation_sent_to_sponsor_date: string | null;
  sent_before_end_of_placement: boolean | null;
  sponsor_completed_date: string | null;
  scholar_comment: string | null;
  sponsor_evaluation_completed_on_time: boolean | null;
  placement_completed_date: string | null;
  placement_performance: string | null;
  placement_grade: string | null;
  grade_updated: string | null;
  grade_updated_date: string | null;
}

// Helper function to compute full_name from first_name and last_name
export const computeFullName = (record: ScholarRecord): string => {
  const firstName = record.first_name || '';
  const lastName = record.last_name || '';
  const fullName = `${firstName} ${lastName}`.trim();
  return fullName || 'N/A';
};

// Extended interface with computed full_name
export interface ScholarRecordWithFullName extends ScholarRecord {
  full_name: string;
}

interface ScholarRecordsResponse {
  total: number;
  scholars: ScholarRecord[];
}

const fetchScholarRecords = async (
  params: ScholarRecordParams
): Promise<ScholarRecordsResponse> => {
  const token = localStorage.getItem('token');
  if (!token) throw new Error('No token found');

  const query = new URLSearchParams();
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null) {
      query.append(key, String(value));
    }
  });

  const res = await fetch(`${BASE_URL}/scholars/full?${query.toString()}`, {
    method: 'GET',
    headers: {
      'Authorization': `Bearer ${token}`,
    },
  });

  if (!res.ok) {
    const err = await res.text();
    throw new Error(`Fetch failed: ${res.status} - ${err}`);
  }

  const data: ScholarRecordsResponse = await res.json();
  return data;
};

// Helper function to transform records and add full_name
export const transformScholarRecords = (records: ScholarRecord[]): ScholarRecordWithFullName[] => {
  return records.map(record => ({
    ...record,
    full_name: computeFullName(record)
  }));
};

export { fetchScholarRecords };
export type { ScholarRecord, ScholarRecordsResponse };